<template>
  <a-modal
    :title="title"
    :width="1400"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model :model="model" :form="form" :rules="rules" ref="form">
        <a-row class="form-row" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="组织" prop="company">
              <j-dict-select-tag
                style="width: 100%"
                placeholder="请选择组织"
                v-model="model.company"
                dictCode="crm_company,name,id"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车间" prop="workshop">
              <j-dict-select-tag placeholder="请选择车间" v-model="model.workshop" dictCode="workshop" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="工序" prop="workingProcedure">
              <j-dict-select-tag
                placeholder="请选择工序"
                v-model="model.workingProcedure"
                dictCode="working_procedure"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="起始班次" prop="shiftInit">
              <j-dict-select-tag placeholder="请选择起始班次" v-model="model.shiftInit" dictCode="shift" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row class="form-row" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="班制" prop="shiftType">
              <!--              <j-dict-select-tag placeholder="请选择班制" v-model="model.shiftSystem" dictCode="shift_type" />-->
              <j-dict-select-tag placeholder="请选择班制" v-model="model.shiftType" dictCode="shift_type" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="设定开始时间" prop="startTime">
              <a-date-picker
                v-model:value="startTime"
                style="width: 100%"
                placeholder="选择日期"
                :allowClear="false"
                @change="onChangeDate"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="设定结束时间" prop="endTime">
              <a-date-picker
                v-model:value="endTime"
                style="width: 100%"
                placeholder="选择日期"
                :allowClear="false"
                @change="onChangeDateEnd"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              v-if="isEdit"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="甲班班长"
              prop="amonitor"
            >
              <m-select-multi-user
                style="width: 215px;"
                v-model="model.amonitor"
                :multiple="false"
                @submitSelect="userSelect($event, 'amonitor')"
                :disabled="false"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-if="isEdit" class="form-row" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="甲班班教" prop="acoach">
              <m-select-multi-user
                style="width: 215px;"
                v-model="model.acoach"
                :multiple="false"
                @submitSelect="userSelect($event, 'acoach')"
                :disabled="false"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="乙班班长" prop="bmonitor">
              <m-select-multi-user
                style="width: 215px;"
                v-model="model.bmonitor"
                :multiple="false"
                @submitSelect="userSelect($event, 'bmonitor')"
                :disabled="false"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="乙班班教" prop="bcoach">
              <m-select-multi-user
                style="width: 215px;"
                v-model="model.bcoach"
                :multiple="false"
                @submitSelect="userSelect($event, 'bcoach')"
                :disabled="false"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              v-if="model.shiftType == '3'"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="丙班班长"
              prop="cmonitor"
            >
              <m-select-multi-user
                style="width: 215px;"
                v-model="model.cmonitor"
                :multiple="false"
                @submitSelect="userSelect($event, 'cmonitor')"
                :disabled="false"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-if="isEdit" class="form-row" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="6">
            <a-form-model-item
              v-if="model.shiftType == '3'"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="丙班班教"
              prop="ccoach"
            >
              <m-select-multi-user
                style="width: 215px;"
                v-model="model.ccoach"
                :multiple="false"
                @submitSelect="userSelect($event, 'ccoach')"
                :disabled="false"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div>
        <div class="shift-table">
          <div class="item" v-for="(day, i) in list" :key="i">
            <div class="th">
              <h3>第{{ i + 1 }}天</h3>
              <h3>{{ day.date | dateFilter }}</h3>
              <div class="time">
                <span>0</span><span>4</span><span>8</span><span>12</span><span>16</span><span>20</span><span>24</span>
              </div>
            </div>
            <div class="td">
              <div
                v-for="(item, index) in day.arr"
                :key="index"
                class="plan"
                :class="{ blue: item.shiftName == '甲班', purple: item.shiftName == '乙班' }"
              >
                <a-row type="flex" justify="space-between">
                  <a-col style="color: #182236">{{ item.shiftName }}</a-col>
                  <span style="color: #48556a">{{ item.diff }}H</span>
                </a-row>
                <div style="white-space: nowrap">({{ item.start }}-{{ item.end }})</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import MSelectMultiUser from './MSelectMultiUser'
import { getShiftSec } from '../../../../api/customApi'
import moment from 'moment'

export default {
  name: 'DeviceModal',

  components: {
    MSelectMultiUser
  },
  data() {
    return {
      title: '操作',
      visible: false,
      disable: true,
      model: {},
      startTime: undefined,
      endTime: undefined,
      isEdit: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      rules: {
        company: [{ required: true, message: '请选择组织', trigger: 'blur' }],
        workshop: [{ required: true, message: '请选择车间', trigger: 'blur' }],
        workingProcedure: [{ required: true, message: '请选择工序', trigger: 'blur' }],
        shift: [{ required: true, message: '请选择起始班次', trigger: 'blur' }],
        shiftSystem: [{ required: true, message: '请选择班制', trigger: 'blur' }]
      },
      url: {
        add: '/crm_shift/crmShift/add',
        edit: '/crm_shift/crmShift/edit'
      },
      list: []
    }
  },
  filters: {
    dateFilter: function(val) {
      if (val) {
        return `${val} | ${moment(val)
          .locale('zh-cn')
          .format('dddd')}`
      }
    }
  },
  created() {},
  methods: {
    userSelect(e, param) {
      this.model[param] = e[0].id
    },
    add() {
      this.disable = false
      this.model = Object.assign({}, {})
      this.edit({}, 1)
      this.isEdit = false
    },
    edit(record, isEdit) {
      if (isEdit != 1) {
        this.model = Object.assign({}, record)
        this.startTime = record.startTime
        this.endTime = record.endTime
        this.isEdit = true
        this.getShiftDetail(this.model.id)
      }

      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.disable = true
      this.$refs.form.resetFields()
      this.startTime = undefined
      this.endTime = undefined
      this.list = []
    },
    async getShiftDetail(bh) {
      const res = await getShiftSec({ shiftId: bh, pageSize: -1 })
      if (res.code == 200) {
        let data = res.result.records
        // 数据构建
        data.map(item => {
          item.day = item.startTime.split(' ')[0]
          item.start = item.startTime.split(' ')[1]
          item.end = item.endTime.split(' ')[1]
          item.diff = Math.round(moment(item.endTime).diff(item.startTime, 'hours', true))
        })
        let arr = this.formatterArr(data, 'day')
        console.log(arr)
        this.list = arr
      }
    },
    formatterArr(arr, group_key) {
      let map = {}
      let res = []
      for (let i = 0; i < arr.length; i++) {
        let ai = arr[i]
        if (!map[ai[group_key]]) {
          map[ai[group_key]] = [ai]
        } else {
          map[ai[group_key]].push(ai)
        }
      }
      Object.keys(map).forEach(key => {
        res.push({ date: key, arr: map[key] })
      })
      return res
    },
    handleOk() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model)
          console.log('formData', formData)
          //时间格式化
          httpAction(httpurl, formData, method)
            .then(res => {
              if (res.success) {
                this.$message.success(res.message)
                this.$emit('ok')
              } else {
                this.$message.warning(res.message)
              }
            })
            .finally(() => {
              this.confirmLoading = false
              this.close()
            })
        } else {
          return false
        }
      })
    },

    handleCancel() {
      this.close()
    },
    onChangeDate(date, dateString) {
      this.model.startTime = dateString
    },
    onChangeDateEnd(date, dateString) {
      this.model.endTime = dateString
    }
  }
}
</script>

<style scoped lang="less">
.shift-table {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(7, 14.3%);
  border: 1px solid #ededed;
  border-left: none;
  margin: 5px 0;

  .item {
    border-bottom: 1px solid #ededed;
    border-left: 1px solid #ededed;

    .th {
      padding: 5px;
      background: rgb(246, 248, 250);
      border-bottom: 1px solid #ededed;

      h3 {
        font-size: 13px;
        font-weight: 500;
        color: #292b3d;
        margin: 0;
        text-align: center;
      }

      .time {
        display: flex;
        justify-content: space-around;

        span {
          font-size: 12px;
          font-weight: 400;
          color: #606d86;
        }
      }
    }

    .td {
      padding: 8px 15px;
      min-height: 54px;

      .plan {
        height: 38px;
        margin-bottom: 8px;
        padding: 3px 7px;
        font-size: 12px;
        color: #48556a;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        border-radius: 2px 0px 0px 2px;
        background: #f4fbf6;
        border-left: 3px solid #48bb94;
      }

      .plan.blue {
        background: #f4f7fb;
        border-left: 3px solid #2c67f6;
      }

      .plan.purple {
        background: #f1eeff;
        border-left: 3px solid #8773f3;
      }

      &.disabled {
        background-color: rgb(248, 249, 251);
      }
    }
  }

  .item:last-child {
    border-right: 1px solid #ededed;
  }
}
</style>
